using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;

using vs.Core;
using vs.Authentication;

namespace Forum
{
    public partial class topic_show : Window
    {
        protected vs.Paging.vsPaging pager;

        #region services
        private void RegistJavascriptEditor()
        {
            SmileController smile = new SmileController();

            string jsInsertSmile = smile.js_insert_smilie(txtContent.ClientID);
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jsInsertSmile", jsInsertSmile);
            lblSmilies.Text = smile.list_images_smilies();

            string jsInsertEditor = smile.js_insert_editor(txtContent.ClientID);
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jsInsertEditor", jsInsertEditor);
            lblEditor.Text = smile.list_images_editor();
        }
        private void VisibleQuickReply()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                tblQuickRely.Visible = false;
                return;
            }

            string strSQL = "SELECT Locked FROM FORUM_Topic WHERE TopicID=@TopicID";
            DataParameter p = new DataParameter("@TopicID", Utils.RequestID());
            object o = DataFactory.ExecuteScalar(strSQL, p);
            if (o != null)
            {
                bool locked = Convert.ToBoolean(o);
                if (locked)
                {
                    tblQuickRely.Visible = false;
                    return;
                }
            }

            tblQuickRely.Visible = true;
        }
        private bool validating()
        {
            txtContent.Text = Utils.KillScript(txtContent.Text);

            if (txtContent.Text.Trim() == "")
            {
                lblMessage.Text = "You have to write your Content";
                lblMessage.Visible = true;
                return false;
            }

            return true;
        }
        private void LoadStaffList()
        {
            if (Authenticate.IsEditor)
            {
                ddlStaff.Visible = true;
                UserDB.FillStaff(ddlStaff);
                RegisterScriptIMG();
            }
        }
        private void RegisterScriptIMG()
        {
            string js = @"
<script language=javascript>
    function popup2 (name,width,height) { 
         var options = ""toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1, width=""+width+"",height=""+height; 
         Cal2=window.open(name,""popup"",options); 
    }

    function SetImage(val)
    {
        val = '[img]' + val + '[/img]';
        var content = document.getElementById('" + txtContent.ClientID + @"');
        if (content.createTextRange && content.caretPos){
            var caretPos = content.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? val + ' ' : val;
        } else { content.value += val; }
        content.focus();
    }
</script>
";

            lnkInsertImage.Visible = true;
            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "setvalue", js);
            string popup = ResolveUrl("~/portal/Galery/ImageGalery.aspx");
            lnkInsertImage.NavigateUrl = "javascript:popup2('" + popup + "', 500, 400);";
        }
        private void show_paging(int topicID, int pg)
        {
            engine_xml engine = new engine_xml();
            int count = engine.CountPageTopic(topicID);
            if (count > 1)
            {
                string topicdesk = this.GetModuleSetting("topicdesk");
                string urlformat = UrlProvider.DesktopUrl(topicdesk, Request.QueryString["ID"], "@@page");
                pager.Visible = true;
                pager.showing(count, pg, urlformat);
            }
            else
            {
                pager.Visible = false;
            }
        }
        private void list_content(int topicID, int pg)
        {
            engine_forum eng = new engine_forum();
            engine_xml engine = new engine_xml();

            string forumID = eng.ForumID2(topicID);
            bool ismod = false;
            if (Request.IsAuthenticated)
            {
                //
                ismod = eng.IsMOD(forumID);
            }
            XmlDocument doc = engine.ShowTopicXML(topicID, pg, ismod);
            string skin = ModSettingController.GetModuleSetting("skin", Utils.ModuleID);
            string template = engine_xml.get_template_folder(skin) + "topic_show.xsl";
            CommonFunction.XMLTransform(xmlTransformer, template, doc);

            Latest();
            SameForum(forumID);

            // update total view
            string strSQL = "UPDATE FORUM_Topic SET TotalView = TotalView + 1 WHERE TopicID=@TopicID";
            DataParameter p = new DataParameter("@TopicID", topicID);
            DataFactory.Execute(strSQL, p);
        }
        private void bind_forum_quick_select(string forumdesk)
        {
            engine_forum engine = new engine_forum();
            DataTable dt = engine.CreateForumTree(forumdesk);
            for (int i = 0; i < dt.Rows.Count; i++)
                ddlForum.Items.Add(new ListItem(dt.Rows[i]["name"].ToString(), dt.Rows[i]["val"].ToString()));
        }
        private string UrlReturn(int topicID)
        {
            // count page
            string strSQL = "select totalreply from forum_topic where topicid=@topicid";
            DataParameter p = new DataParameter("@topicid", topicID);
            object o = DataFactory.ExecuteScalar(strSQL, p);
            int rows = Convert.ToInt32(o);
            int countPage = rows / engine_forum.REPLY_PER_PAGE;
            if (countPage * engine_forum.REPLY_PER_PAGE < rows) countPage++;

            // return url
            string topicdesk = this.GetModuleSetting("topicdesk");
            string url = UrlProvider.DesktopUrl(topicdesk, topicID.ToString());
            if (countPage > 1)
                url = UrlProvider.DesktopUrl(topicdesk, topicID.ToString(), countPage.ToString());
            return url;
        }
        private XmlDocument Gendoc(DataTable dt, string topicdesk)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<topics></topics>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                XmlElement topic = doc.CreateElement("topic");

                string topicID = dt.Rows[i]["TopicID"].ToString();
                string vn = engine_xml.ToVN(dt.Rows[i]["TopicName"].ToString());
                string url = UrlProvider.DesktopUrl(topicdesk, topicID + "_" + vn);

                CommonFunction.AddNode(doc, topic, "link", url);
                CommonFunction.AddNode(doc, topic, "TopicName", dt.Rows[i]["TopicName"].ToString());
                CommonFunction.AddNode(doc, topic, "PostedDate", CommonFunction.ToDateString(Convert.ToDateTime(dt.Rows[i]["PostedDate"]), "dd-MM-yy hh:mm"));

                doc.DocumentElement.AppendChild(topic);
            }
            return doc;
        }
        private void Latest()
        {
            string strSQL = "SELECT TopicID, TopicName, PostedDate FROM FORUM_Topic ORDER BY PostedDate DESC";
            DataTable dt = DataFactory.LoadPage(strSQL, 0, 10);
            XmlDocument doc = Gendoc(dt, PortalUtils.CurrentDesktopName);
            string template = "/desktops/forum/template/relatedtopics.xsl";
            CommonFunction.XMLTransform(xmlLatest, template, doc);
        }
        private void SameForum(string forumID)
        {
            string strSQL = "SELECT TopicID, TopicName, PostedDate FROM FORUM_Topic WHERE (ForumID=@ForumID) ORDER BY PostedDate DESC";
            DataParameter p = new DataParameter("@ForumID", forumID);
            DataTable dt = DataFactory.LoadPage(strSQL, 0, 10, p);
            XmlDocument doc = Gendoc(dt, PortalUtils.CurrentDesktopName);
            string template = "/desktops/forum/template/relatedtopics.xsl";
            CommonFunction.XMLTransform(xmlSameForum, template, doc);
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    if (Request.QueryString["ID"] == null) return;

                    int topicID = Utils.RequestID();
                    int pg = 0;
                    if (Request.QueryString["catID"] != null)
                        pg = Convert.ToInt32(Request.QueryString["catID"]) - 1;

                    string forumdesk = this.GetModuleSetting("forumdesk");

                    list_content(topicID, pg);
                    show_paging(topicID, pg);
                    if (forumdesk != "")
                        bind_forum_quick_select(forumdesk);

                    if (Request.IsAuthenticated)
                        LoadStaffList();

                    VisibleQuickReply();
                    RegistJavascriptEditor();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }

        protected void btnReply_Click(object sender, EventArgs e)
        {
            try
            {
                if (!validating()) return;

                if (!Request.IsAuthenticated) return;

                if (txtContent.Text.Trim() == "")
                {
                    lblMessage.Text = "You have to write anything!";
                    lblMessage.Visible = true;
                    return;
                }

                string username = HttpContext.Current.User.Identity.Name;
                if (vs.Authentication.Authenticate.CurrentUser.Staff)
                    username = ddlStaff.SelectedValue;
                engine_xml xml = new engine_xml();
                engine_forum engine = new engine_forum();
                int topicID = Utils.RequestID();
                engine.InsertReplyContent(txtContent.Text.Trim(), topicID, username);
                DataCache.ResetPrefix(engine_xml.REPLY_LIST_CACHE_PREFIX);
                DataCache.RemoveCache(topic_lastest.CACHE_LATEST_TOPIC);

                //redirect
                string url = UrlReturn(topicID);
                Response.Redirect(url);
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
                lblMessage.Visible = true;
            }
        }

        protected void ddlForum_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlForum.SelectedValue != "")
                Response.Redirect(ddlForum.SelectedValue);
        }
    }
}